package stackandqueue.queue.circularqueue;

import stackandqueue.queue.inter.Queue;

/**
 * 循环队列
 *
 * @param <T>
 */
public class CircularQueue<T> implements Queue<T> {
    private int front;
    private int rear;
    private T[] arr;
    private int maxSize;
    private int queueLength;

    public CircularQueue() {
        this(7);
    }

    public CircularQueue(int maxSize) {
        front = 0;
        rear = 0;
        this.maxSize = maxSize;
        queueLength = 0;
        arr = (T[]) new Object[maxSize];
    }

    @Override
    public void clearQueue() {
        rear = front;
        queueLength = 0;
    }

    @Override
    public boolean queueEmpty() {
        return queueLength() == 0;
    }

    @Override
    public T getHead() {
        T t = null;
        if (queueLength() > 0) {
            t = arr[front];
        }
        return t;
    }

    @Override
    public void enQueue(T e) {
        if (queueLength() == 0 || rear != front) {
            arr[rear] = e;
            rear = (rear + 1) % maxSize;
            queueLength++;
        }
    }

    @Override
    public T deQueue() {
        T t = null;
        if (queueLength() > 0) {
            t = arr[front];
            front = (front + 1) % maxSize;
            queueLength--;
        }
        return t;
    }

    @Override
    public int queueLength() {
        return queueLength;
    }
}
